<template>
  <div>
    <div class="app-container">
      <div class="app-container-inner" v-loading="loading" element-loading-text="加载中...">
        <div style="display: flex; gap: 5px; margin-bottom: 10px; justify-content: flex-end">
          <HPlainButton @click="submitForm(ruleFormRef)">保存</HPlainButton>
          <HButton @click="cancelSave">取消</HButton>
        </div>
        <div class="card">
          <h3>品牌信息</h3>
          <div class="form">
            <el-form
              label-width="80"
              ref="ruleFormRef"
              :rules="rules"
              :model="ruleForm"
              :inline="true"
              class="demo-form-inline"
            >
              <div class="form_content">
                <el-form-item label="品牌名称" class="el-item" prop="name">
                  <el-input
                    clearable
                    v-model="ruleForm.name"
                    :title="ruleForm.name"
                    class="item-name"
                    placeholder="请输入品牌名称"
                  />
                </el-form-item>
                <el-form-item label="公司名称" class="el-item">
                  <el-input
                    clearable
                    v-model="input1"
                    :title="input1"
                    class="item-name"
                    placeholder="请输入公司名称"
                  />
                </el-form-item>
                <el-form-item label="品牌电话" class="el-item rule-phone" prop="phone">
                  <el-input
                    clearable
                    v-model="ruleForm.phone"
                    class="item-input"
                    placeholder="请输入品牌电话"
                  />
                </el-form-item>
                <el-form-item label="品牌编码" class="el-item" prop="code">
                  <el-input
                    clearable
                    v-model="ruleForm.code"
                    :title="ruleForm.code"
                    class="item-name"
                    placeholder="不填写则系统生成"
                  />
                </el-form-item>
                <el-form-item label="公司地址" class="el-item">
                  <div :title="addrTitle" style="height: 28px; display: flex; align-items: center">
                    <SingleAddress
                      @value-change="handleAddressUpdate"
                      ref="addrsDom"
                      :address="addrs"
                    />
                  </div>
                </el-form-item>
                <el-form-item label="详细地址" class="el-item">
                  <el-input
                    clearable
                    v-model="input2"
                    :title="input2"
                    class="addr-detail"
                    maxlength="200"
                    placeholder="详细地址"
                  />
                </el-form-item>
              </div>

              <!--品牌标志-->
              <el-form-item label="品牌标志">
                <div class="upload-card">
                  <div class="img" v-if="imgUrl1">
                    <img :src="imgUrl1" alt="" />
                    <div class="img_mask">
                      <el-icon @click="onPreviewBrandLogo">
                        <zoom-in />
                      </el-icon>
                      <el-icon @click="onDelBrandLogo">
                        <Delete />
                      </el-icon>
                    </div>
                  </div>
                  <el-upload
                    v-else
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="getUrl1"
                  >
                    <el-icon class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item>

              <!--公众号-->
              <!-- <el-form-item label="公众号">
                <div class="upload-card">
                  <div class="img" v-if="imgUrl2">
                    <img :src="imgUrl2" alt="" />
                    <div class="img_mask">
                      <el-icon @click="onPreviewPublicNumberImg">
                        <zoom-in />
                      </el-icon>
                      <el-icon @click="onDelPublicNumberImg">
                        <Delete />
                      </el-icon>
                    </div>
                  </div>
                  <el-upload
                    v-else
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="getUrl2"
                  >
                    <el-icon class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item> -->
            </el-form>
          </div>
        </div>
        <div class="list mt10">
          <div class="text flex-justify-between">
            <div style="display: flex; align-items: center; gap: 5px">
              <h3>参数信息 </h3>
              <div style="display: flex; align-items: center; gap: 5px">
                <el-switch v-model="paraShow" class="switch-item" />
                <span style="color: #333" v-if="paraShow">启用</span>
                <span style="color: #333" v-else>禁用</span>
              </div>
            </div>
            <span style="color: #007cff">找不到参数？试试自定义参数</span>
          </div>
          <div class="item" v-show="paraShow == true">
            <div class="add">
              <HPlainButton @click="addText">增加</HPlainButton>
            </div>
            <div class="para-form">
              <el-form :inline="true" class="demo-form-inline">
                <el-form-item label="序号" class="item-num"> </el-form-item>
                <el-form-item label="参数名称" class="item-name"> </el-form-item>
                <el-form-item label="参数内容"> </el-form-item>
              </el-form>
              <el-form
                ref="ruleFormRef2"
                label-width="80"
                :inline="true"
                class="demo-form-inline"
                :rules="rules"
                v-for="(item, index) in items"
                :key="index"
              >
                <el-form-item class="form-item">
                  <span class="para-num">{{ index + 1 }}</span>
                </el-form-item>
                <el-form-item class="form-item">
                  <el-input v-model="item.name" class="para-name" clearable />
                </el-form-item>
                <el-form-item class="form-item">
                  <el-input v-model="item.val" class="para-val" clearable />
                </el-form-item>
                <el-form-item class="form-item">
                  <HLink type="error" @click="handleDele(index, item)">删除</HLink>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
        <div class="card mt10 edior">
          <h3 class="brand-edior">品牌介绍</h3>
          <WangEdior :all_data="ediorData" ref="wangEdior" />
        </div>

        <el-dialog
          v-model="imgPreviewModalVisible"
          title="图片预览"
          @close="onCloseImgPreviewModal"
        >
          <div style="display: flex; justify-content: center">
            <img :src="imgPreviewUrl" alt="" />
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import SingleAddress from '@/components/address/singleAddress.vue'
  import WangEdior from '@/components/WangEdior/index.vue'
  import { saveBrand } from '@/api/brand'
  import { ref, reactive, onMounted } from 'vue'
  import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
  import type { UploadProps, FormInstance, UploadFile } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { useSettingStore } from '@/store/modules/setting'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { getBrandDetail } from '@/api/brand'
  import { proAnnexUpload } from '@/api/upload'
  import { useRoute, useRouter } from 'vue-router'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.good.brandForm,
  })

  const TagsViewStore = useTagsViewStore()
  const route = useRoute()
  const router = useRouter()
  const SettingStore = useSettingStore()
  const loading = ref(false)
  const addrs = ref({}) // 公司地址
  const addrTitle = ref('')
  const input1 = ref('') // 公司名称
  const input2 = ref('') // 详细地址
  const status = ref() // 品牌状态
  const paraShow = ref(false) // 是否启用参数
  const showCode = ref(false)

  const addrsDom = ref()

  // 品牌介绍内容 HTML
  const wangEdior = ref()
  const ediorData = ref({ content: '', type: 'goods' })

  // 参数数量
  const items = ref([
    {
      name: '',
      val: '',
    },
  ])

  const itemIds = ref([]) // 删除品牌参数ID集合

  // 图片地址 1-品牌标志 2-公众号
  const imgUrl1 = ref('')
  const imgUrl2 = ref('')

  const mark = ref()
  const publicNo = ref()

  // 表单数据
  const ruleForm = reactive({
    name: '', // 品牌名称
    code: '', // 品牌名称,
    phone: '', // 品牌电话
  })

  // 表单元素
  const ruleFormRef = ref<FormInstance>()
  const ruleFormRef2 = ref<FormInstance>()

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
    code: [{ required: false, message: '请输入品牌编码', trigger: 'blur' }],
    phone: [
      { required: false, message: '请输入正确的品牌电话', trigger: 'blur' },
      {
        pattern:
          /^((12[0-9])|(13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0|1,5-9])|(19[0-9])|(17[0-9]))\d{8}$/,
        message: '电话号码格式不正确',
        trigger: 'blur',
      },
    ],
    paraName: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
    paraVal: [{ required: true, message: '请输入参数内容', trigger: 'blur' }],
  })

  onMounted(async () => {
    // 判断是  新增/修改  id 有值为修改品牌
    if (route.params.id != undefined) {
      loading.value = true
      await getBrandDetail(route.params.id).then((res) => {
        rules.code[0].required = true
        const row = res.data.data.row
        ruleForm.name = row.name
        ruleForm.code = row.code
        showCode.value = true
        status.value = row.status
        input1.value = row.company
        ruleForm.phone = row.telephone
        addrs.value = {
          province: row.province,
          city: row.city,
          area: row.area,
          town: row.town,
        }
        addrTitle.value = row.province + '-' + row.city + '-' + row.area + '-' + row.town
        input2.value = row.address
        imgUrl1.value = row.mark
        imgUrl2.value = row.publicNo
        items.value = row.brandParamVos
        ediorData.value = { content: row.describe, type: 'goods' }
        if (row.brandParamVos.length != 0) {
          paraShow.value = true
        }
      })
      loading.value = false
    }
  })

  // 删除参数内容
  const handleDele = (i, obj) => {
    items.value.splice(i, 1)
    if (obj.id) {
      itemIds.value.push(obj.id)
    }
  }

  // 新增参数内容
  const addText = () => {
    if (items.value.some((o) => !(o.name && o.val))) {
      ElMessage({
        message: '请填写完整参数信息！',
        type: 'warning',
        duration: 2000,
      })
      return
    }
    const tmp = {
      name: '',
      val: '',
    }
    items.value.push(tmp)
  }

  // 图片预览弹窗状态
  const imgPreviewModalVisible = ref(false)

  // 图片预览地址
  const imgPreviewUrl = ref('')

  // 图片预览弹窗关闭事件
  const onCloseImgPreviewModal = () => {
    imgPreviewModalVisible.value = false
    imgPreviewUrl.value = ''
  }

  // 品牌标志上传事件
  const getUrl1: UploadProps['onChange'] = (uploadFile: UploadFile) => {
    imgUrl1.value = window.URL.createObjectURL(uploadFile.raw)
    mark.value = uploadFile.raw
  }

  // 删除品牌标志图片
  const onDelBrandLogo = () => {
    imgUrl1.value = ''
    mark.value = null
  }

  // 预览品牌标志
  const onPreviewBrandLogo = () => {
    imgPreviewModalVisible.value = true
    imgPreviewUrl.value = imgUrl1.value
  }

  // 公众号图片上传事件
  const getUrl2: UploadProps['onChange'] = (uploadFile: UploadFile) => {
    imgUrl2.value = window.URL.createObjectURL(uploadFile.raw)
    publicNo.value = uploadFile.raw
  }

  // 删除品牌标志图片
  const onDelPublicNumberImg = () => {
    imgUrl2.value = ''
    publicNo.value = null
  }

  // 预览品牌标志
  const onPreviewPublicNumberImg = () => {
    imgPreviewModalVisible.value = true
    imgPreviewUrl.value = imgUrl2.value
  }

  // 地址
  const address = ref({
    province: '',
    area: '',
    city: '',
    town: '',
  })

  // 地址更新事件
  const handleAddressUpdate = (addr: {
    province: string
    area: string
    city: string
    town: string
  }) => {
    Object.assign(address.value, { ...addr })
  }

  // 保存数据
  const submitForm = (formEl: FormInstance | undefined) => {
    let tmp = []
    if (paraShow.value == true) {
      if (items.value.some((o) => !(o.name && o.val))) {
        ElMessage({
          message: '请填写完整参数信息！',
          type: 'warning',
          duration: 2000,
        })
        return
      }
      items.value.forEach((item) => {
        tmp.push({
          name: item.name,
          val: item.val,
        })
      })
    }

    // 新增的品牌数据
    const data = {
      name: ruleForm.name, // 品牌名称
      status: false, // 品牌状态：false-启用，true-禁用
      address: input2.value, // 公司地址-详细地址
      area: address.value.area, // 公司地址-县/区
      brandParamIds: itemIds.value, // 删除品牌参数ID集合
      brandParamVos: tmp, // 品牌参数
      city: address.value.city, // 公司地址-市
      code: ruleForm.code, // 品牌编码
      company: input1.value, // 公司名称
      describe: wangEdior.value.getValue(), // 品牌介绍
      mark: '', // 品牌标志路径
      province: address.value.province, // 公司地址-省
      publicNo: '', // 公众号
      telephone: ruleForm.phone, // 品牌电话
      town: address.value.town, // 公司地址-镇
    }

    // 修改的品牌数据
    const data2 = {
      id: route.params.id, // 品牌id
      name: ruleForm.name, // 品牌名称
      status: status.value, // 品牌状态：false-启用，true-禁用
      address: input2.value, // 公司地址-详细地址
      area: address.value.area, // 公司地址-县/区
      brandParamIds: itemIds.value, // 删除品牌参数ID集合
      brandParamVos: items.value, // 品牌参数
      city: address.value.city, // 公司地址-市
      code: ruleForm.code, // 品牌编码
      company: input1.value, // 公司名称
      describe: wangEdior.value.getValue(), // 品牌介绍
      mark: '', // 品牌标志路径
      province: address.value.province, // 公司地址-省
      publicNo: '', // 公众号
      telephone: ruleForm.phone, // 品牌电话
      town: address.value.town, // 公司地址-镇
    }

    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        loading.value = true
        if (imgUrl1.value) {
          const files = []
          files.push(mark.value)
          if (files.length != 0) {
            await proAnnexUpload(files).then((res) => {
              data.mark = res.data.data.rows[0]
              data2.mark = res.data.data.rows[0]
              imgUrl1.value = res.data.data.rows[0]
            })
          }
        }
        if (imgUrl2.value) {
          const files = []
          files.push(publicNo.value)
          if (files.length != 0) {
            await proAnnexUpload(files).then((res) => {
              data.publicNo = res.data.data.rows[0]
              data2.publicNo = res.data.data.rows[0]
              imgUrl2.value = res.data.data.rows[0]
            })
          }
        }
        wangEdior.value.getDeleteImages()
        if (route.params.id != undefined) {
          // 修改品牌
          await saveBrand(data2).then((res) => {
            if (res.data.success == true) {
              ElMessage({
                message: res.data.message,
                type: 'success',
                duration: 2000,
              })
              SettingStore.setReload()
              TagsViewStore.delView(route.path) // 关闭当前页面
              router.push('/busic/base/proset?active=brandSet')
              loading.value = false
            } else {
              if (res.data.isError)
                ElMessage({
                  message: res.data.message,
                  type: 'warning',
                  duration: 2000,
                })
              loading.value = false
              return
            }
          })
        } else {
          // 新增品牌
          await saveBrand(data).then((res) => {
            if (res.data.success == true) {
              ElMessage({
                message: res.data.message,
                type: 'success',
                duration: 2000,
              })
              SettingStore.setReload()
              TagsViewStore.delView(route.path) // 关闭当前页面
              router.push('/busic/base/proset?active=brandSet')
              loading.value = false
            } else {
              if (res.data.isError)
                ElMessage({
                  message: res.data.message,
                  type: 'warning',
                  duration: 2000,
                })
              loading.value = false
              return
            }
          })
        }
      } else {
        return
      }
    })
  }

  // 取消保存
  const cancelSave = () => {
    TagsViewStore.delView(route.path) // 关闭当前页面
    router.go(-1) // 返回列表页面
  }
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
